#include "FindPwd.h"
#include "ui_FindPwd.h"

FindPwd::FindPwd(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::FindPwd)
{
    ui->setupUi(this);
    setFixedSize(270,150);
    ui->stackedWidget->setCurrentIndex(0);
    ui->nextBtn0->setFocus();// 间接去掉输入框的焦点（比较好看）
    initValidator();// 初始化验证器
}

FindPwd::~FindPwd()
{
    delete ui;
}

void FindPwd::initValidator()
{
    // 设置正则表达式对象
    QRegularExpression idRegExp("^[1-9][0-9]{11}$");// 账号：12位纯数字，第一位不能是0
    QRegularExpression pwdRegExp("^[a-zA-Z0-9]{1,8}$");// 密码：1-8位，仅包含英文大小写和数字
    QRegularExpressionValidator* idValidator = new QRegularExpressionValidator(idRegExp,ui->idLineEdit0);
    QRegularExpressionValidator* pwdValidator = new QRegularExpressionValidator(pwdRegExp,ui->pwdLineEdit);
    ui->idLineEdit0->setValidator(idValidator);
    ui->pwdLineEdit->setValidator(pwdValidator);
    ui->pwd2LineEdit->setValidator(pwdValidator);
}

void FindPwd::on_nextBtn0_clicked()
{
    // 判断是否为空
    QString id = ui->idLineEdit0->text();
    if(id.isEmpty()){
        QMessageBox::warning(this,"警告","请输入账号");
        return;
    }

    // 发信号给主类，让其发送给服务端
    emit findPwdStep1(id);
    ui->idLineEdit0->setEnabled(false);
    ui->nextBtn0->setEnabled(false);
}

void FindPwd::onFindPwdStep1(const QString reply, const QString safeQ)
{
    if(reply == "faild"){
        QMessageBox::warning(this,"警告","账号不存在");
        ui->idLineEdit0->setEnabled(true);
        ui->nextBtn0->setEnabled(true);

    }else if(reply == "succeed"){
        ui->stackedWidget->setCurrentIndex(1);
        ui->safeQPlainTextEdit->setPlainText(safeQ);
        ui->nextBtn1->setFocus();// 间接去掉输入框的焦点（比较好看）
    }
}

void FindPwd::onFindPwdStep2(const QString reply)
{
    if(reply == "faild"){
        QMessageBox::warning(this,"警告","回答错误");
        ui->safeALineEdit->setEnabled(true);
        ui->nextBtn1->setEnabled(true);

    }else if(reply == "succeed"){
        ui->stackedWidget->setCurrentIndex(2);
        ui->finishBtn->setFocus();// 间接去掉输入框的焦点（比较好看）
    }
}


void FindPwd::on_nextBtn1_clicked()
{
    // 判断是否回答了
    QString safeA = ui->safeALineEdit->text();
    if(safeA.isEmpty()){
        QMessageBox::warning(this,"警告","请进行回答");
        return;
    }

    ui->safeALineEdit->setEnabled(false);
    ui->nextBtn1->setEnabled(false);

    QString id = ui->idLineEdit0->text();
    // 回给登录主类，让其发送给服务端
    emit findPwdStep2(id, safeA);
}


void FindPwd::on_finishBtn_clicked()
{
    QString pwd = ui->pwdLineEdit->text();
    QString pwd2 = ui->pwd2LineEdit->text();
    if(pwd.isEmpty()){
        QMessageBox::warning(this,"警告","请输入密码");
        return;
    }
    else if(pwd2.isEmpty()){
        QMessageBox::warning(this,"警告","请确认密码");
        return;
    }
    else if(pwd != pwd2){
        QMessageBox::warning(this,"警告","密码不一致");
        return;
    }

    QString id = ui->idLineEdit0->text();

    // 将信息发送回主类
    emit findPwdStep3(id, pwd);
    this->close();// 关闭找回密码窗口
}

